#include "fifo.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * 函数：模拟FIFO（先进先出）页面置换算法。
 *
 * @param queue_frames 一个字符串，表示页面访问序列。
 *                     字符串中的每个字符是一个数字，表示一个页面号。
 * @param num_frames   页框的数量，表示物理内存中可用的页框数。
 */
void
fifo_page_replacement (char *queue_frames, int num)
{
  // TODO
  int *frames = (int *)malloc (num * sizeof (int));
  int *order = (int *)malloc (num * sizeof (int));
  int frame_count = 0;
  int front = 0;

  for (int i = 0; i < num; i++)
    {
      frames[i] = -1;
      order[i] = -1;
    }

  char *token = strtok (queue_frames, ",");
  while (token != NULL)
    {
      int page = atoi (token);
      int found = 0;

      for (int i = 0; i < frame_count; i++)
        {
          if (frames[i] == page)
            {
              found = 1;
              break;
            }
        }

      if (!found)
        {
          if (frame_count < num)
            {
              frames[frame_count] = page;
              order[frame_count] = page;
              frame_count++;
            }
          else
            {
              int oldest = order[front];
              for (int i = 0; i < num; i++)
                {
                  if (frames[i] == oldest)
                    {
                      frames[i] = page;
                      break;
                    }
                }
              order[front] = page;
              front = (front + 1) % num;
            }
        }

      printf ("Access:%d,Frames: [", page);
      for (int i = 0; i < num; i++)
        {
          if (i != 0)
            {
              printf (",");
            }
          if (frames[i] != -1)
            {
              printf ("%d", frames[i]);
            }
          else
            {
              printf ("-1");
            }
        }
      printf ("]\n");

      token = strtok (NULL, ",");
    }

  free (frames);
  free (order);
}
